import _camelCase from 'lodash/camelCase'
import _kebabCase from 'lodash/kebabCase'
import _isFunction from 'lodash/isFunction'
import _cloneDeep from 'lodash/cloneDeep'

/**
 *
 * @param  object {object}
 * @returns {object}
 */
export const convertCamelcase = object => {
  const newObject = {}
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      newObject[_camelCase(key)] = object[key]
    }
  }
  return newObject
}

/**
 *
 * @param  object {object}
 * @returns {object}
 */
export const convertKebabCase = object => {
  const newObject = {}
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      newObject[_kebabCase(key)] = object[key]
    }
  }
  return newObject
}

/**
 *
 * @param  self {any} vue this
 * @param  key {string} attr name
 */
export const getAttrs = (self, key) => {
  if (self.$attrs[_kebabCase(key)]) {
    return self.$attrs[_kebabCase(key)]
  }

  if (self.$attrs[_camelCase(key)]) {
    return self.$attrs[_camelCase(key)]
  }
}

/**
 *
 * @param  self {any}  vue this
 * @param  key {string} event name
 */
export const getListener = (self, key) => {
  const listener = self.$listeners
  if (listener[_kebabCase(key)]) {
    return listener[_kebabCase(key)]
  }

  if (listener[_camelCase(key)]) {
    return listener[_camelCase(key)]
  }
}

/**
 *
 * @param  self {any} vue this
 * @param  name {string} slot name
 */
export const getSlot = (self, name = 'default') => {
  return (
    self.$scopedSlots?.[name] ||
    self.$slots?.[name] ||
    getScopedSlots(self)?.[name]
  )
}

/**
 *
 * @param  self {any} vue this
 */
export const getScopedSlots = self => {
  return self.$vnode.data?.scopedSlots || {}
}

/**
 * @param options { any }
 * @param params { any }
 * @param props { Array<string> }
 * @returns any
 */
export const handlePropsMethod = (
  options = {},
  { row, column },
  props = []
) => {
  const _options = _cloneDeep(options)
  props.forEach(key => {
    const prop = _options[key]
    if (prop && _isFunction(prop)) {
      _options[key] = prop({ cellValue: row[column.property], row, column })
    }
  })
  return _options
}

function getEventTargetNode(evnt, className) {
  let targetElem
  let target = evnt.target

  while (target?.nodeType && target !== document) {
    if (target?.className?.split(' ').indexOf(className) > -1) {
      targetElem = target
    } else if (target === document.body) {
      return !!targetElem
    }

    target = target.parentNode
  }

  return false
}
export function clearEvent(params, e) {
  const evnt = params.$event || e
  const classList = [
    'el-autocomplete-suggestion',
    'el-select-dropdown',
    'el-cascader__dropdown',
    'el-cascader-menus',
    'el-time-panel',
    'el-picker-panel',
    'el-color-dropdown'
  ]
  return !classList.some(i => getEventTargetNode(evnt, i))
}
